<?php

class RegisterController extends ControllerBase
{
    public function initialize()
    {
        $this->tag->setTitle('用户注册');
        parent::initialize();
    }

	private function setInitValues($array)
	{
		foreach ($array as $key => $value ) {
			$this->view->setVar($key, $value);
		}
	}

    /**
     * Action to register a new user
     */
    public function indexAction()
	{
        if ($this->request->isPost()) {

            $name = $this->request->getPost('name', array('string', 'striptags'));
            $username = $this->request->getPost('username', 'alphanum');
            $email = $this->request->getPost('email', 'email');
            $password = $this->request->getPost('password');
            $repeatPassword = $this->request->getPost('repeatPassword');

            if ($password != $repeatPassword) {
                $this->flash->error('两次输入密码不一致！');
				$this->setInitValues ($this->request->getPost());
                return false;
            }

            $user = new Users();
            $user->username = $username;
            $user->password = sha1($password);
            $user->name = $name;
            $user->email = $email;
            $user->active = 'Y';
            if ($user->save() == false) {
				
				foreach ($user->getMessages() as $message) {
                    $this->flash->error((string) $message);
                }
				$this->setInitValues ($this->request->getPost());

            } else {

                $this->tag->setDefault('email', '');
                $this->tag->setDefault('password', '');
                $this->flash->success('感谢你的注册，请登录，开始使用！');
				return $this->forward('session/index');

            }
        }
		else {
			$this->setInitValues (array (
				"name" => '',
				"username" => '',
				"email" => '',
				"password" => '',
				"repeatPassword" => ''
			));
		}
    }
}
